<?php echo $this->headLink()->appendStylesheet('/css/redmond/jquery-ui-1.8.5.custom.css') ?>
<?php echo $this->headLink()->appendStylesheet('/css/poshytip-1.0/tip-yellowsimple/tip-yellowsimple.css') ?>
<script type="text/javascript" src="/jquery/jquery.blockUI.js"></script>
<script type="text/javascript" src="/jquery/jquery.validate.js"></script> 
<script type="text/javascript" src="/jquery/poshytip-1.0/jquery.poshytip.js"></script> 
<script type="text/javascript">
$(document).ready(function() { 
	var registerBlk = $('#registerBlk')[0];
    $('#hplRegister').click(function() { 
        $.blockUI({ 
            message: $(registerBlk),
            fadeIn: 500, 
            fadeOut: 500,
            css: { 
        		top: '100px',
                width: '400px',
                cursor: 'auto',
                '-webkit-border-radius': '10px', 
                '-moz-border-radius': '10px'
            } 
        });
    });

    $('#btnCancelReg').click(function(){
    	$.unblockUI(); 
    });

    $("#frmLogin").validate({
		highlight: function(element, errorClass) {
	    	$(element).css({ backgroundColor: "rgb(240,150,150)"});
	    },
	    unhighlight: function(element, errorClass) {
	        $(element).css({ backgroundColor: "rgb(160,255,165)"});
	    },
	    rules:
        {
	    	"username": {
	        	required: true
	        },
	        "password": {
	        	required: true,
	       		minlength: 6
	        }
        },
	    messages: {
        	"username": {
	       		required: "請輸入電郵地址"
	        },
	        "password": {
	       		required: "請輸入密碼",
	       		minlength: "最少6位數字密碼"
	        }
        }
	});

    $.validator.addMethod(
    	"pw", 
    	function(value, element) {   
      		return this.optional(element) || /^(|[A-Za-z0-9_])*$/.test(value);   
    	}, 
    	"密碼只能包括英文字、數字和下劃線");   
    
    $("#frmRegister").validate({
    	highlight: function(element, errorClass) {
        	$(element).css({ backgroundColor: "rgb(240,150,150)"});
        },
        unhighlight: function(element, errorClass) {
            $(element).css({ backgroundColor: "rgb(160,255,165)"});
        },
        rules: 
        {
        	"username": {
        		required: true,
        		remote: {
        			url: "/ajax/verifyUsername.php"
                }
            },
            "password": {
            	required: true,
           		minlength: 6,
           		pw: true
            },
        	"confirm": {
                required: true,
                minlength: 6,
                equalTo: "#txtPassword1"
            },
            "email": {
    			required: true,
    			email: true,
    			remote: {
        			url: "/ajax/verifyEmail.php"
                }
            },
            "phone": {
    			required: true,
    			minlength: 8,
    			digits: true,
    			remote: {
        			url: "/ajax/verifyPhone.php"
            	}
            },
            "imgfile":{
                accept: "jpg|gif"
            }
        },
        messages: {
            "username": {
           		required: "請輸入用戶名稱",
           		remote: "用戶名稱已被使用"
            },
            "password": {
           		required: "請輸入密碼",
           		minlength: "最少6個字元密碼"
            },
            "confirm": {
           		required: "請輸入確認密碼",
           		minlength: "最少6個字元確認密碼",
           		equalTo: "與先前輸入的密碼不符合"
            },
            "email": {
           		required: "請輸入電郵地址",
           		email: "錯誤的電郵格式",
           		remote: "電郵地址已被使用"
            },
            "phone": {
           		required: "請輸入手機號碼",
           		minlength: "請輸入正確手機號碼",
           		digits: "請輸入正確手機號碼",
           		remote: "手機號碼已被使用"
            },
            "imgfile": {
    			accept: "只能上傳JPG或GIF格式圖片"
    	   	}
        }
    });
    
    $('.register').poshytip({
    	className: 'tip-yellowsimple',
    	showOn: 'focus',
    	alignTo: 'target',
    	alignX: 'center',
    	alignY: 'top',
    	offsetY: 5
    });

    $('textarea[maxlength]').keyup(function(){
		var max = parseInt($(this).attr('maxlength'));
		if($(this).val().length > max){
			$(this).val($(this).val().substr(0, $(this).attr('maxlength')));
        }
        $(this).parent().find('.charsRemaining').html('You have ' + (max - $(this).val().length) + ' characters remaining');
   	});
});
</script>
<?php 
$sessLogin = new Zend_Session_Namespace('Login');
require_once '/fb/facebook-php-sdk-42481fa/src/facebook.php';
	
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
	'appId'  => '354578754618136',
	'secret' => '3eeb1509e2cd4a6faa369eb80c99ebc6',
));

// Get User ID
$user = $facebook->getUser();

// We may or may not have this data based on whether the user is logged in.
//
// If we have a $user id here, it means we know the user is logged into
// Facebook, but we don't know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.

if ($user) {
  try {
    // Proceed knowing you have a logged in user who's authenticated.
    $user_profile = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
    $user = null;
  }
}

// Login or logout url will be needed depending on current user state.
if ($user) {
  $logoutUrl = $facebook->getLogoutUrl(array(
  	'next'=>'http://www.thingslook.com/member/logout')
  );
} else {
  $loginUrl = $facebook->getLoginUrl(array(
  	'scope' => 'email,user_about_me,user_hometown,user_photos')
  );
}

// This call will always work since we are fetching public data.
$naitik = $facebook->api('/naitik');
?>
<?php 
	$member_mapper = new Application_Model_MemberMapper();
	$country_mapper = new Application_Model_CountryMapper();
	$product_buy_bid_mapper = new Application_Model_ProductBuyBidMapper();
	
	$offerCounter = 0;
	$cOfferCounter = 0;
	
	$mbmEntry = null;
	if($sessLogin->mbmId != null){
    	$mbmEntry = $member_mapper->findByMemberId($sessLogin->mbmId);
    	
	
		$pbBidEntries = $product_buy_bid_mapper->findByMemberIdOfferType($sessLogin->mbmId, 'CO');
		$cOfferCounter += sizeof($pbBidEntries);
		
		$pbBidEntries = $product_buy_bid_mapper->findNoticeByMemberIdOfferType($sessLogin->mbmId, 'O');
		$offerCounter += sizeof($pbBidEntries);
	}
	else if($user){
		$mbmEntry = $member_mapper->findByEmail($user_profile['email']);
		
		//If a facebook user doesn't have thingslook account, register automatically.
		if(sizeof($mbmEntry[0]) < 1){
			$member_model = new Application_Model_Member();
			$member_mapper = new Application_Model_MemberMapper();
			Zend_Date::setOptions(array('format_type' => 'php'));
			$date = new Zend_Date();
			$code = rand(100000,999999);
			
			$member_model->setUsername($user_profile["first_name"] . " " . $user_profile['last_name']);
			$member_model->setEmail($user_profile['email']);
			$member_model->setMember_type('normal');
			$member_model->setGender(strtoupper(substr($user_profile['gender'],0,1)));
			$member_model->setBirth('0000-00-00 00:00:00');
			$member_model->setImage('http://graph.facebook.com/' . $user . '/picture?type=large');
			$member_model->setDeal_credit(100);
			$member_model->setRating_credit(0);
			$member_model->setTotal_deal(0);
			$member_model->setCreation_time($date->toString('Y-m-d H:i:s'));
			$member_model->setCode($code);
			
			$member_mapper->insertAll($member_model);
			$mbmEntry = $member_mapper->findByEmail($user_profile['email']);
			header('Location: http://www.thingslook.com/member/editform');
		}
		
		$sessLogin->mbmId = $mbmEntry[0]->member_id;
		
		$pbBidEntries = $product_buy_bid_mapper->findNoticeByMemberIdOfferType($mbmEntry[0]->member_id, 'O');
		$offerCounter += sizeof($pbBidEntries);
		
		$pbBidEntries = $product_buy_bid_mapper->findByMemberIdOfferType($mbmEntry[0]->member_id, 'CO');
		$cOfferCounter += sizeof($pbBidEntries);
	}
?>

<div id="header">
	<div id="header-content">
		<?php 
			if ($sessLogin->mbmId != null){ 
		?>
			<div id="logout-box">
				<form id="frmLogout" method='post' action='/member/logout'>
					<table>
						<tr>
							<td><a class="hplMenu" href='/product/findseller'>主頁</a></td>
							<td><a class="hplMenu" href='/member/profile/mid/own'>帳戶資料</a></td>
							<td><a class="hplMenu" href='/member/editform'>修改帳戶資料</a></td>
							<td><a class="hplMenu" href='/member/myproduct'>我的拍賣&nbsp;<label class='lblNotice'><?php if($offerCounter != 0){echo $offerCounter;}else{echo "0";}?></label></a></td>
							<td><a class="hplMenu" href='/member/mybid'>我的投標&nbsp;<label class='lblNotice'><?php if($cOfferCounter != 0){echo $cOfferCounter;}else{echo "0";}?></label></a></td>
							<td><a class="hplMenu" href="/member/schedule">行事曆</a></td>
							<td><a class="hplMenu" href="/member/relation/type/f">好友名單</a></td>
							<td><a class="hplMenu" href="/member/relation/type/b">黑名單</a></td>
							<td><?php echo $mbmEntry[0]->username;?>你好</td>
							<td>
								<?php if($user){
								?>
									<a id="btnLogout" class="yellow-button" name='logout' href="<?php echo $logoutUrl; ?>">登出</a>
								<?php 
								}else if($sessLogin->mbmId != null){
								?>
									<input id="btnLogout" class="yellow-button" type='submit' name='logout' value='登出'>
								<?php }?>
							</td>
						</tr>
					</table>
				</form>
			</div>
		<?php 
			}
			else{
		?>
			<div id="login-box">
				<table>
					<tr>
						<td>
							<form id="frmLogin" method='post' action='/member/login/re/sell'>
								<table>
									<tr>
										<td><input id="txtUsername" type='text' name='username' placeholder="電郵地址"/></td>
										<td><input id="txtPassword" type='password' name='password' placeholder="密碼"/></td>
										<td><input id="btnLogin" class="yellow-button" type='submit' name='login' value='登入'></td>
									</tr>
									<tr>
										<td><input type="checkbox" name="rmbMe" value="Y" id="chkEmbMe"/>記住我</td>
										<td><a href="/member/forgetpassword">忘記密碼?</a></td>
										<td><a id="hplRegister">或註冊</a></td>
									</tr>
								</table>
							</form>
						</td>
						<td>&nbsp;&nbsp;或&nbsp;&nbsp;</td>
						<td><a href="<?php echo $loginUrl; ?>"><img id="btnFbLogin" src="/images/layout/fb_login.jpg" width="160px"/></a></td>
					</tr>
				</table>
			</div>
		<?php
			} 
		?>
	</div>
</div>
<div id="registerBlk" class="blockUI">
	<div class="header">會員註冊</div>
	<form id="frmRegister" method='post' action='/member/register' enctype='multipart/form-data'>
		<table>
			<tr>
				<td style="width:80px">用戶名稱</td>
				<td style="width:320px"><input type='text' id='txtUsername' name='username' class='register' title="只接受中文字、英文字、數字和下劃線"/></td>
			</tr>
			<tr>
				<td>密碼</td>
				<td><input type='password' id='txtPassword1' name='password' class='register' title="只接受英文字、數字和下劃線及最少輸入6個字元"/></td>
			</tr>	
			<tr>
				<td>確認密碼</td>
				<td><input type='password' id='txtConfirm' name='confirm' class='register' title="必需與先前輸入的密碼相符"/></td>
			</tr>
			<tr>
				<td>電子郵箱</td>
				<td><input type='text' id='txtEmail' name='email' class='register' title="一個電郵地址只可作一次申請"/></td>
			</tr>
			<tr>
				<td>手提電話</td>
				<td><input type='text' id='txtPhone' name='phone' class='register' maxlength='8' title="請輸入正確的手機號碼，此號碼會用作驗證之用"/></td>
			</tr>
			<tr>
				<td>性別</td>
				<td>
					<select name='gender'>
						<option value=''></option>
						<option value='M'>男</option>
						<option value='F'>女</option>
					</select>
				</td>
			</tr>
			<tr>
				<td>常駐地區</td>
				<td>
					<select name="travel">
						<option value=""></option>
						<?php 
						$countryEntries = $country_mapper->findAll();
						for($i = 0;$i < sizeof($countryEntries); $i++){
						?>
						<option value="<?php echo $countryEntries[$i]->abbrev;?>"><?php echo $countryEntries[$i]->country_name;?></option>
						<?php 
						}
						?>
					</select>
				</td>
			</tr>
			<tr>
				<td>職業</td>
				<td><input type='text' id='txtJob' name='job' class='register'/></td>
			</tr>
			<tr>
				<td>個人頭像</td>
				<td><input type="file" name="imgfile"></td>
			</tr>
			<tr>
				<td>自我簡介</td>
				<td><textarea id='txtDescription' name='description' placeholder="只限40字" maxlength="40" rows="2" cols="30"></textarea></td>
			</tr>
			<tr>
				<td><label for="subject">輸入驗證碼</label></td>
				<td>
					<?php 
						$CHALLENGE_FIELD_PARAM_NAME = "verificationCode";
					?>
					<input type="text" 
						name="<?php echo($CHALLENGE_FIELD_PARAM_NAME) ?>" 
						id="<?php echo($CHALLENGE_FIELD_PARAM_NAME) ?>" 
						maxlength="<?php echo($CHALLENGE_STRING_LENGTH) ?>" 
						size="<?php echo($CHALLENGE_STRING_LENGTH) ?>" 
						class="inputText" />
					<img src="/function/DRBImageVerification/getimage.php" />
				</td>
			</tr>
			<tr>
				<td colspan="2">
					<p class='policy'>
						當你按下「提交」按鈕時，則表示你已閱讀並同意 ThingsLook
						<a href='/footer/condition' target='_blank'>服務條款</a>
						和
						<a href='/footer/privacy' target='_blank'>私隱政策</a>
						 ，並同意從 ThingsLook接收與你的帳戶相關的電郵通知。	
					</p>
					<input type='submit' name='register' value='提交' />
					<input type='button' id="btnCancelReg" value='取消' />
				</td>
			</tr>
		</table>
	</form>
</div>